package com.newtouch.bxzs.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.PersonalCustomer;
import com.newtouch.bxzs.common.base.model.PersonalCustomerGroup;
import com.newtouch.bxzs.common.base.model.PersonalCustomerGroupMap;
import com.newtouch.bxzs.common.base.util.EntityToBeanUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import com.newtouch.bxzs.enterprise.controller.PersonalCustomerController;
import com.newtouch.bxzs.enterprise.mapper.PersonalCustomerGroupMapMapper;
import com.newtouch.bxzs.enterprise.mapper.PersonalCustomerGroupMapper;
import com.newtouch.bxzs.enterprise.mapper.PersonalCustomerMapper;
import com.newtouch.bxzs.enterprise.model.bo.CustomerBO;
import com.newtouch.bxzs.enterprise.model.bo.PersonalCustomerBO;
import com.newtouch.bxzs.enterprise.model.bo.PersonalCustomerGroupBO;
import com.newtouch.bxzs.enterprise.model.vo.CustomerVO;
import com.newtouch.bxzs.enterprise.model.vo.PersonalCustomerGroupVO;
import com.newtouch.bxzs.enterprise.service.PersonalCustomerGroupService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 个人分组实现类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2020/12/25 9:48</td>
 * <td>yuanjie</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author yuanjie
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class PersonalCustomerGroupServiceImpl implements PersonalCustomerGroupService {

    @Autowired
    private PersonalCustomerGroupMapper personalCustomerGroupMapper;

    @Autowired
    private PersonalCustomerGroupMapMapper personalCustomerGroupMapMapper;

    @Autowired
    private PersonalCustomerMapper personalCustomerMapper;

    /**
     * 静态变量：系统日志
     */
    private static final Log logger = LogFactory.getLog(PersonalCustomerController.class);

    @Override
    public List<PersonalCustomerGroupBO> getGroupList() {
        /*获取当前分组信息*/
        List<PersonalCustomerGroupBO> groupList = personalCustomerGroupMapper.getGroupList(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        /*判断是否为空*/
        if (CollectionUtils.isEmpty(groupList)) {
            return Collections.emptyList();
        }
        return groupList;
    }

    @Override
    public String modifyPersonalCustomerGroup(PersonalCustomerGroupVO personalCustomerGroupVO) {
        /*判断传入是否为空*/
        if (BeanUtil.isEmpty(personalCustomerGroupVO)) {
            return null;
        }
        PersonalCustomerGroup group = new PersonalCustomerGroup();
        BeanUtil.copyProperties(personalCustomerGroupVO, group);
        /*判断分组ID是否为空，为空新增，不为空修改*/
        if (StringUtils.isEmpty(group.getGroupId())) {
            /*判断分组是否存在*/
            if (!checkGroupName(group.getGroupName())) {
                throw new BaseException(BaseErrorEnum.DATA_EXISTS);
            }
            group.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            group.setCreateTime(new Date());
            group.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            group.setUpdateTime(new Date());
            personalCustomerGroupMapper.insert(group);
            logger.info("分组增加成功");
        } else {
            /*修改*/
                if (!checkGroupName(group.getGroupName())) {
                throw new BaseException(BaseErrorEnum.DATA_EXISTS);
            }
            group.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            group.setUpdateTime(new Date());
            personalCustomerGroupMapper.updateById(group);
            logger.info("分组修改成功");
        }
        return group.getGroupId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String deletePersonalCustomerGroup(PersonalCustomerGroupVO personalCustomerGroupVO) {
        if (BeanUtil.isEmpty(personalCustomerGroupVO)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        /*判断是否为空*/
        if (personalCustomerGroupMapper.deleteBatchIds(personalCustomerGroupVO.getGroupIds()) == 1) {
            /*移除分组中的客户*/
            personalCustomerGroupMapMapper.delete(new QueryWrapper<PersonalCustomerGroupMap>().in("GROUP_ID", personalCustomerGroupVO.getGroupIds()));
        }
        return "已删除分组";
    }

    @Override
    public String insertGroupCustomer(PersonalCustomerGroupVO personalCustomerGroupVO) {
        /*判断是否为空*/
        if (BeanUtil.isEmpty(personalCustomerGroupVO)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        /*创建一个 分组客户集合*/
        List<PersonalCustomerGroupMap> personalCustomerGroupMapList = new ArrayList<>();
        /*批量插入,遍历客户ID,存入PersonalCustomerGroupMap对象中*/
        for (String customerId : personalCustomerGroupVO.getCustomerIds()) {
            PersonalCustomerGroupMap personalCustomerGroupMap = new PersonalCustomerGroupMap();
            personalCustomerGroupMap.setGroupId(personalCustomerGroupVO.getGroupId());
            personalCustomerGroupMap.setCustomerId(customerId);
            personalCustomerGroupMap.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            personalCustomerGroupMap.setCreateTime(new Date());
            personalCustomerGroupMap.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            personalCustomerGroupMap.setUpdateTime(new Date());
            /*将对象加入分组客户集合中*/
            personalCustomerGroupMapList.add(personalCustomerGroupMap);
        }
        if (CollectionUtils.isEmpty(personalCustomerGroupMapList)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        personalCustomerGroupMapMapper.insertBach(personalCustomerGroupMapList);
        return "分组客户已添加成功";
    }

    @Override
    public Integer deleteGroupCustomer(PersonalCustomerGroupVO personalCustomerGroupVO) {
        /*判断是否为空*/
        if (BeanUtil.isEmpty(personalCustomerGroupVO)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        /*移除在分组客户关联表中存在客户*/
        QueryWrapper<PersonalCustomerGroupMap> qw = new QueryWrapper<>();
        qw.in("CUSTOMER_ID", personalCustomerGroupVO.getCustomerIds()).eq("GROUP_ID",personalCustomerGroupVO.getGroupId());
        return personalCustomerGroupMapMapper.delete(qw);
    }

    @Override
    public CustomerBO getEnableAddCustomerList(CustomerVO customerVO) {
        CustomerBO customerBO = new CustomerBO();
        /*判断分组Id是否为空*/
        if (BeanUtil.isEmpty(customerVO)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        QueryWrapper<PersonalCustomerGroupMap> qw = new QueryWrapper<>();
        qw.eq("GROUP_ID", customerVO.getGroupId());
        /*根据分组ID查询出所有客户集合*/
        List<PersonalCustomerGroupMap> groupCustomerList = personalCustomerGroupMapMapper.selectList(qw);
        QueryWrapper<PersonalCustomer> query = new QueryWrapper<>();
        query.eq("USER_JOB_NUMBER", Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserJobNumber()).like("CUSTOMER_NAME", StringUtils.isEmpty(customerVO.getCustomerName()) ? "" : customerVO.getCustomerName());
        List<PersonalCustomer> personalCustomerList;
        /*当分组客户不会空时,筛选分组中存在的客户*/
        if (!CollectionUtils.isEmpty(groupCustomerList)) {
            /*客户ID集合*/
            List<String> customerIdList = new ArrayList<>();
            /*循环遍历出客户ID加入 customerList 里面*/
            for (PersonalCustomerGroupMap personalCustomerGroupMap : groupCustomerList) {
                customerIdList.add(personalCustomerGroupMap.getCustomerId());
            }
            /*不包含已存在的客户*/
            query.notIn("CUSTOMER_ID", customerIdList);
            /*筛选出不包含分组存在的客户*/
            personalCustomerList = personalCustomerMapper.selectList(query);
        } else {
            /*分组客户为空时,查询所有客户*/
            personalCustomerList = personalCustomerMapper.selectList(query);
        }
        /*存入集合*/
        customerBO.setList(EntityToBeanUtils.copyBean(personalCustomerList, PersonalCustomerBO.class));
        customerBO.setCount(personalCustomerList.size());
        return customerBO;
    }
    /**
     * 判断分组是否存在
     *
     * @param groupName 分组名称
     * @return groupList是否为空
     */
    private Boolean checkGroupName(String groupName) {
        /*校验必填项*/
        if (StringUtils.isEmpty(groupName)) {
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
        /*判断分组名称是否存在*/
        List<PersonalCustomerGroup> groupList = personalCustomerGroupMapper.selectList(
                new QueryWrapper<PersonalCustomerGroup>()
                        .eq("GROUP_NAME", groupName).eq("CREATE_USER_ID",Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId()));
        return CollectionUtils.isEmpty(groupList);
    }

}
